package com.bs.service;

import com.bs.domain.PartitionIp2Host;
import com.bs.domain.Partitions;
import com.bs.repository.PartitionIp2HostRepository;
import com.bs.repository.PartitionsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wenguangjia on 2017/7/25.
 */
@Service
@Transactional
public class PartitionIp2HostService {
    @Autowired
    private PartitionIp2HostRepository partitionIp2HostRepository;

    public List<PartitionIp2Host> getAll(PartitionIp2Host partitionIp2Host){
       return partitionIp2HostRepository.findAll(where(partitionIp2Host));
    }

    public void save(PartitionIp2Host partitionIp2Host){
        partitionIp2HostRepository.save(partitionIp2Host);
    }

    public void delete(Long id){
        partitionIp2HostRepository.delete(id);
    }

    /**
     * 条件查询时动态组装条件
     */
    private Specification<PartitionIp2Host> where(PartitionIp2Host partitionIp2Host) {
        return new Specification<PartitionIp2Host>() {
            @Override
            public Predicate toPredicate(Root<PartitionIp2Host> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                //ename
                if (partitionIp2Host.getHost() != null && !partitionIp2Host.getHost().equals("")) {
                    predicates.add(cb.equal(root.<String>get("host"), partitionIp2Host.getHost()));
                }
                return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
